package com.zzxz.practicaltrainingsys.controller;

import com.github.pagehelper.PageInfo;
import com.zzxz.practicaltrainingsys.entity.Homeworkfinish;
import com.zzxz.practicaltrainingsys.service.HomeworkfinishService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/homeworkfinish")
@CrossOrigin
public class HomeworkfinishController {
    @Autowired
    private HomeworkfinishService homeworkfinishService;

    //查看所有完成作业
    @GetMapping("/list")
    public List<Homeworkfinish> queryAllHomeworkfinish() {
        return homeworkfinishService.queryAllHomeworkfinish();
    }

    //查看具体某个项目的所有完成作业
    // http://localhost:8080/homeworkfinish/find?id=
    @GetMapping("/pro")
    public List<Homeworkfinish> getProHomeworkfinishById(Integer id) {
        return homeworkfinishService.getProHomeworkfinishById(id);
    }

    //根据homework_id查找这次作业的完成作业
    @GetMapping("/find")
    public List<Homeworkfinish> getProHomeworkfinishhById(Integer id) {
        return homeworkfinishService.getHomeHomeworkfinishById(id);
    }

    //查看某条完成作业详细
    @GetMapping("/detail")
    public Homeworkfinish getDetailHomeworkfinishById(Integer id) {
        return homeworkfinishService.getDetailHomeworkfinishById(id);
    }

    //用来查询所有完成作业信息（联合项目表、学生表、作业发布信息表）
    //http://localhost:8080/homeworkfinish/all
    @GetMapping("/all")
    public ResponseEntity<?> getAllHomeworkfinish() {
        try {
            System.out.println("开始调用 getAllHomeworkfinish 方法");
            List<Map<String, Object>> result = homeworkfinishService.getAllHomeworkfinish();
            System.out.println("getAllHomeworkfinish 调用成功，返回数据条数: " + (result != null ? result.size() : 0));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            System.err.println("getAllHomeworkfinish 方法发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    //分页查询
    @ApiOperation("查找作业发布信息（分页查询）")
    @GetMapping("/pages")
    public ResponseEntity<?> getPagesHomeworkfinishList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            System.out.println("开始调用分页查询，pageNum: " + pageNum + ", pageSize: " + pageSize);

            if (pageNum == null || pageNum < 1) {
                pageNum = 1;
            }
            if (pageSize == null || pageSize < 1) {
                pageSize = 10;
            }

            PageInfo<Map<String, Object>> pageInfo = homeworkfinishService.findHomeworkfinishPages(pageNum, pageSize);
            System.out.println("分页查询调用成功");
            return ResponseEntity.ok(pageInfo);
        } catch (Exception e) {
            System.err.println("分页查询方法发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 在 HomeworkfinishController.java 中添加以下方法

    // 获取某个学生的所有已提交作业
    @GetMapping("/student/{studentId}")
    public ResponseEntity<?> getStudentHomeworks(@PathVariable Integer studentId) {
        try {
            System.out.println("获取学生作业，学生ID: " + studentId);
            List<Homeworkfinish> result = homeworkfinishService.getHomeworksByStudentId(studentId);
            System.out.println("获取学生作业成功，返回数据条数: " + (result != null ? result.size() : 0));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            System.err.println("获取学生作业发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 获取学生某个作业的提交详情
    @GetMapping("/detail/student/{studentId}/homework/{homeworkId}")
    public ResponseEntity<?> getStudentHomeworkDetail(
            @PathVariable Integer studentId,
            @PathVariable Integer homeworkId) {
        try {
            System.out.println("获取学生作业详情，学生ID: " + studentId + ", 作业ID: " + homeworkId);
            Homeworkfinish result = homeworkfinishService.getStudentHomeworkDetail(studentId, homeworkId);
            System.out.println("获取学生作业详情成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            System.err.println("获取学生作业详情发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 学生提交作业
    @PostMapping("/insert")
    public ResponseEntity<?> insertHomeworkfinish(@RequestBody Homeworkfinish homeworkfinish) {
        try {
            System.out.println("学生提交作业: " + homeworkfinish);
            int result = homeworkfinishService.insertHomeworkfinish(homeworkfinish);

            Map<String, Object> response = new HashMap<>();
            response.put("success", result > 0);
            response.put("message", result > 0 ? "作业提交成功" : "作业提交失败");
            response.put("data", result);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("学生提交作业发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 学生更新作业
    @PutMapping("/update")
    public ResponseEntity<?> updateHomeworkfinish(@RequestBody Homeworkfinish homeworkfinish) {
        try {
            System.out.println("学生更新作业: " + homeworkfinish);
            int result = homeworkfinishService.updateHomeworkfinish(homeworkfinish);

            Map<String, Object> response = new HashMap<>();
            response.put("success", result > 0);
            response.put("message", result > 0 ? "作业更新成功" : "作业更新失败");
            response.put("data", result);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("学生更新作业发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            errorResponse.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 判断小组作业
    @GetMapping("/team/{teamId}/homework/{homeworkId}")
    public ResponseEntity<?> getTeamHomeworkDetails(
            @PathVariable Integer teamId,
            @PathVariable Integer homeworkId) {
        try {
            List<Homeworkfinish> result = homeworkfinishService.getTeamHomeworkDetails(teamId, homeworkId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    //判断组长及组号
    @GetMapping("/is-leader/{studentId}/team/{teamId}")
    public ResponseEntity<?> isTeamLeader(
            @PathVariable Integer studentId,
            @PathVariable Integer teamId) {
        try {
            boolean result = homeworkfinishService.isTeamLeader(studentId, teamId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 获取学生所在团队信息
    @GetMapping("/get-student-team/{studentId}/{projectId}")
    public ResponseEntity<?> getStudentTeam(
            @PathVariable Integer studentId,
            @PathVariable Integer projectId) {
        try {
            Map<String, Object> teamInfo = homeworkfinishService.getStudentTeamInfo(studentId, projectId);
            return ResponseEntity.ok(teamInfo);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }


    @PostMapping("/grade-individual")
    public ResponseEntity<?> gradeIndividualHomework(@RequestBody Map<String, Object> params) {
        try {
            // 安全地获取Integer参数
            Integer homeworkId = getIntegerFromMap(params, "homework_id");
            Integer studentId = getIntegerFromMap(params, "student_id");
            String homeworkMarks = (String) params.get("homework_marks");
            String teacherComment = (String) params.get("teacher_comment");

            System.out.println("批改个人作业，作业ID: " + homeworkId + ", 学生ID: " + studentId);

            int result = homeworkfinishService.gradeIndividualHomework(homeworkId, studentId, homeworkMarks, teacherComment);

            Map<String, Object> response = new HashMap<>();
            response.put("success", result > 0);
            response.put("message", result > 0 ? "批改成功" : "批改失败");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("批改个人作业发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @PostMapping("/grade-team")
    public ResponseEntity<?> gradeTeamHomework(@RequestBody Map<String, Object> params) {
        try {
            // 安全地获取Integer参数
            Integer homeworkId = getIntegerFromMap(params, "homework_id");
            Integer teamId = getIntegerFromMap(params, "team_id");
            String homeworkMarks = (String) params.get("homework_marks");
            String teacherComment = (String) params.get("teacher_comment");

            System.out.println("批改小组作业，作业ID: " + homeworkId + ", 小组ID: " + teamId);

            int result = homeworkfinishService.gradeTeamHomework(homeworkId, teamId, homeworkMarks, teacherComment);

            Map<String, Object> response = new HashMap<>();
            response.put("success", result > 0);
            response.put("message", result > 0 ? "批改成功" : "批改失败");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("批改小组作业发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @PostMapping("/return-individual")
    public ResponseEntity<?> returnIndividualHomework(@RequestBody Map<String, Object> params) {
        try {
            Integer homeworkId = getIntegerFromMap(params, "homework_id");
            Integer studentId = getIntegerFromMap(params, "student_id");
            Integer homeworkBack = getIntegerFromMap(params, "homework_back");

            System.out.println("打回个人作业，作业ID: " + homeworkId + ", 学生ID: " + studentId);

            int result = homeworkfinishService.returnIndividualHomework(homeworkId, studentId, homeworkBack);

            Map<String, Object> response = new HashMap<>();
            response.put("success", result > 0);
            response.put("message", result > 0 ? "打回成功" : "打回失败");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("打回个人作业发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @PostMapping("/return-team")
    public ResponseEntity<?> returnTeamHomework(@RequestBody Map<String, Object> params) {
        try {
            Integer homeworkId = getIntegerFromMap(params, "homework_id");
            Integer teamId = getIntegerFromMap(params, "team_id");
            Integer homeworkBack = getIntegerFromMap(params, "homework_back");

            System.out.println("打回小组作业，作业ID: " + homeworkId + ", 小组ID: " + teamId);

            int result = homeworkfinishService.returnTeamHomework(homeworkId, teamId, homeworkBack);

            Map<String, Object> response = new HashMap<>();
            response.put("success", result > 0);
            response.put("message", result > 0 ? "打回成功" : "打回失败");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("打回小组作业发生异常:");
            e.printStackTrace();

            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务器内部错误");
            errorResponse.put("message", e.getMessage());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 添加辅助方法来安全地从Map中获取Integer值
    private Integer getIntegerFromMap(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        if (value instanceof Integer) {
            return (Integer) value;
        }
        if (value instanceof String) {
            try {
                return Integer.valueOf((String) value);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("无法将参数 " + key + " 转换为整数: " + value);
            }
        }
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        throw new IllegalArgumentException("参数 " + key + " 的类型不支持转换为整数: " + value.getClass());
    }
}
